package leilei.jace.com.tcpdemo2.client;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import leilei.jace.com.tcpdemo2.R;
import leilei.jace.com.tcpdemo2.listener.onClientNotifition;
import leilei.jace.com.tcpdemo2.service.MyService;
import leilei.jace.com.tcpdemo2.text.FristTextEvent;
import leilei.jace.com.tcpdemo2.text.SmartCarProtocol;
import leilei.jace.com.tcpdemo2.util.LogUtil;
import leilei.jace.com.tcpdemo2.util.MyUtil;
import leilei.jace.com.tcpdemo2.util.NettyConfig;

public class MainActivity extends AppCompatActivity implements onClientNotifition {
    //    private ScreenReceiver screenReceiver = new ScreenReceiver();
    private EditText edttext;
    private TextView showip;
    private ExecutorService executorService = Executors.newFixedThreadPool(20);
    public static final String SERVICE_MESSAGE = "SERVICE_MESSAGE";
    public static final String CLIENT_MESSAGE = "CLIENT_MESSAGE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        showip = (TextView) findViewById(R.id.showip);
        edttext = (EditText) findViewById(R.id.edttext);
        showip.setText(MyUtil.getIP());
    }

    public void sendMsg1(View view) {
        TcpClient.getInstance().StartTcpClient(edttext.getText().toString());
    }

    public void sendMsg2(View view) {
        StringBuilder builder = new StringBuilder();
        builder.append(edttext.getText().toString());
        String data = builder.toString();
        // 获得要发送信息的字节数组
        byte[] content = data.getBytes();
        // 要发送信息的长度
        int contentLength = content.length;
        SmartCarProtocol protocol = new SmartCarProtocol(contentLength, content);
        NettyConfig.client_group.writeAndFlush(protocol);
    }

    public void sendMsg3(View view) {
        showip.setText(MyUtil.getIP() + "");
    }

    public void startService(View view) {
        Intent intent = new Intent(MainActivity.this, MyService.class);
        startService(intent);
    }

//    private void start(String hostname) throws Exception {
//        EventLoopGroup group = new NioEventLoopGroup();
//        try {
//            Bootstrap b = new Bootstrap();//创建Bootstrap
//            b.group(group)
//                    .channel(NioSocketChannel.class)
//                    .option(ChannelOption.TCP_NODELAY, true)
//                    .option(ChannelOption.SO_KEEPALIVE, true)
//                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
//                    .handler(new LoggingHandler(LogLevel.INFO))
//                    .remoteAddress(new InetSocketAddress(hostname, 9998))
//                    .handler(new ChannelInitializer<io.netty.channel.socket.SocketChannel>() {
//                        @Override
//                        protected void initChannel(io.netty.channel.socket.SocketChannel ch) throws Exception {
//                            ch.pipeline().addLast(new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS));
//                            ch.pipeline().addLast(new SmartCarEncoder());
//                            ch.pipeline().addLast(new SmartCarDecoder());
//                            ch.pipeline().addLast(new ClientHandler());
//                        }
//                    });
//            ChannelFuture channelFuture = b.connect().sync();//连接到远程节点,阻塞等待直到连接完成
//            if (channelFuture.isSuccess()) {
//                LogUtil.e("远程节点连接成功", "远程节点连接成功");
//            } else {
//                LogUtil.e("远程节点连接失败", "远程节点连接失败");
//            }
//            channelFuture.channel().closeFuture().sync();//阻塞，直到Channel关闭
//        } finally {
//            group.shutdownGracefully();//关闭线程池并且释放所有的资源
//        }
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        Intent intent = new Intent(MainActivity.this, MyService.class);
        stopService(intent);
    }

    @Override
    public void clientNotifition(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showip.setText(msg);
            }
        });
    }

    @Subscribe
    public void onEventMainThread(final FristTextEvent event) {
        LogUtil.e("收到的eventbus标记==", event.getmMsg() + "===");
        switch (event.getTag()) {
            case SERVICE_MESSAGE:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showip.setText(event.getmMsg());
                    }
                });
                break;
            case CLIENT_MESSAGE:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showip.setText(event.getmMsg());
                    }
                });
                break;
        }
    }
}
